package com.qili.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.annotation.TokenCheck;
import com.qili.base.entity.CurrentUser;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.affaircase.AffairCase;
import com.qili.entity.affaircase.AffairRecord;
import com.qili.entity.affaircase.dto.AffairCaseDTO;
import com.qili.entity.affaircase.dto.AffairRecordDTO;
import com.qili.entity.base.BaseCompany;
import com.qili.entity.base.BaseCompanyOwner;
import com.qili.entity.base.BaseDict;
import com.qili.entity.jc.JcProject;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.ProjectLeaderDTO;
import com.qili.entity.supervisor.dto.ProjectNoticeDTO;
import com.qili.entity.supervisor.dto.ProjectUnitConstructionDTO;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.SupplierProjectChange;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.supplier.dto.*;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.entity.zx.ZxProject;
import com.qili.exception.MyException;
import com.qili.service.AffairService;
import com.qili.service.SysUserService;
import com.qili.service.WorkflowService;
import com.qili.service.affairCase.AffairCaseService;
import com.qili.service.affairCase.AffairRecordService;
import com.qili.service.base.BaseCompanyOwnerService;
import com.qili.service.base.BaseCompanyService;
import com.qili.service.base.BaseDictService;
import com.qili.service.jc.JcProjectService;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.sys.SysRegionService;
import com.qili.service.zx.ZxProjectService;
import com.qili.util.*;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author zhaoyongke
 * @date 2021/10/21
 * @description app 流程处理
 */

@Controller
@Slf4j
@RequestMapping("/app/lc")
public class AppLcController {

    @Autowired
    SupervisorProjectService supervisorProjectService;
    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    AffairCaseService affairCaseService;
    @Autowired
    AffairRecordService affairRecordService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    ProjectLeaderService projectLeaderService;
    @Autowired
    ProjectContractService projectContractService;
    @Autowired
    ProjectAdminService projectAdminService;
    @Autowired
    WorkflowService workflowService;
    @Autowired
    ProjectUnitConstructionService projectUnitConstructionService;
    @Autowired
    ProjectSealRecordService projectSealRecordService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    ProjectPlaceService projectPlaceService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    SupplierProjectManagerChangeService supplierProjectManagerChangeService;
    @Autowired
    ProjectPlaceChangeService projectPlaceChangeService;
    @Autowired
    SupervisorFileTempService supervisorFileTempService;
    @Autowired
    SupervisorProjectModifiedRecordService supervisorProjectModifiedRecordService;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    AffairService affairService;

    @Autowired
    ZxProjectService zxProjectService;

    @Autowired
    JcProjectService jcProjectService;

    @Autowired
    private BaseCompanyOwnerService baseCompanyOwnerService;


    @Autowired
    SupervisorProjectModifiedRecordService modifiedRecordService;

    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 查询代码事项
     * @Date:15:12 2020/11/12
     */
    @PostMapping(value = "queryTaskList")
    @ResponseBody
    @TokenCheck
    public JsonUtil queryMyTodoSh(@RequestBody AffairCaseDTO dto, HttpServletRequest request) {
        JsonUtil reJs = new JsonUtil();
        //加载类型
        String jztype = request.getParameter("jztype") + "";
        String userId = dto.getUserId();
        if (StringUtils.isBlank(jztype) || StringUtils.isBlank(userId)) {
            reJs.setMsg("参数获取失败！！");
            reJs.setFlag(false);
            return reJs;
        }
        try {
            // 总监理工程师
            /*     dto.setUserId("acfc0e9232f54732a5d9ffe9071bf572");*/
            //技术负责人
            /*    dto.setUserId("9fd9e24a31e946be905146f49dd9b0f2");*/

            //查询类型 1 代办 2 已办理 自己参与的流程未结束 3 已办结 自己参与的 流程已办结 4 我的请求 自己发起的流程 5 审批进程 所有参与的流程
            // 除代办查询，其他如果一个流程有多个任务节点 查询结果只显示一条
            String lbType = dto.getLbType();
            List<AffairCaseDTO> ListRe = null;
            if ("1".equals(lbType)) {
                dto.setUserId(userId);
//                if("002".equals(jztype)){
//                    fylimit();
//                }
                ListRe = affairService.queryMyTodoShApp(dto);

                System.out.println(ListRe);

            } else if ("2".equals(lbType)) {
                //已办事宜
                dto.setUserId(userId);
//                if("002".equals(jztype)){
//                    fylimit();
//                }
                ListRe = affairService.queryMyHisSh(dto);
            } else if ("3".equals(lbType)) {
                dto.setOperUserId(userId);
                //办结事宜  参与过的流程 已经办结的case
//                if("002".equals(jztype)){
//                    fylimit();
//                }
                ListRe = affairService.queryBjCase(dto);
            } else if ("4".equals(lbType)) {
                // 我的请求 我发起的
                dto.setUserId(userId);
//                if("002".equals(jztype)){
//                    fylimit();
//                }
                ListRe = affairService.queryMyFqCaseApp(dto);
            } else if ("0".equals(lbType)) {
                AffairCaseDTO notice = new AffairCaseDTO();
                notice.setSendTo(userId);
                notice.setApplicantType(dto.getApplicantType());
//                if("002".equals(jztype)){
//                    fyNoticelimit();
//                }
                ListRe = affairService.queryMyNoticeApp(notice);
                for (int i = 0; i < ListRe.size(); i++) {
                    AffairCaseDTO affairCaseDTO = ListRe.get(i);
                    String caseId = affairCaseDTO.getCaseId();
                    ProjectNotice projectNotice = projectNoticeServie.selectByPrimaryKey(caseId);
                    projectNotice.setIsView("1");
                    projectNoticeServie.updateByPrimaryKey(projectNotice);

                }
                System.out.println("消息");
            } else if ("6".equals(lbType)) {
                // 全部
                dto.setOperUserId(userId);
//                if("002".equals(jztype)){
//                    fylimit();
//                }
                ListRe = affairService.queryMyFqCase(dto);
            }
            reJs.setMsg("获取成功。");
            reJs.setFlag(true);
            reJs.setData(ListRe);
            return reJs;
        } catch (Exception e) {
            e.printStackTrace();
            reJs.setMsg("获取失败！！" + e.getMessage());
            reJs.setFlag(false);
            return reJs;
        }
    }


    @PostMapping("processCheckDetail")
    @ResponseBody
    @TokenCheck
    public JsonUtil processCheckDetail(@RequestBody AffairCaseDTO dto, Model model, HttpServletRequest request) {
        HashMap map = new HashMap();
        String url = "";
        try {
            AffairCase affairCase = new AffairCase();
            affairCase.setCaseId(dto.getCaseId());
            affairCase = affairCaseService.selectByPrimaryKey(affairCase);
            String yqType = dto.getLcType();// 流程查看类型 1  代办 2 已办  3 已办结 4 我的请求 5 审批进程
            String userId = dto.getUserId();
            // 查询流程记录表
            AffairRecordDTO recorddto = new AffairRecordDTO();
            recorddto.setYwId(dto.getCaseId());
            List<AffairRecordDTO> listRecord = affairRecordService.selectRecord(recorddto);
            if (listRecord != null && listRecord.size() > 0) {
                for (int i = 0; i < listRecord.size(); i++) {
                    if (StringUtil.isBlank(listRecord.get(i).getRemark())) {
                        listRecord.get(i).setRemark("");
                    }
                }
            }
            map.put("listRecord", listRecord);
            if ("000".equals(affairCase.getLcType())) {
                BeanUtil.copyNotNullBean(affairCase, dto);
                dto.setLcType(yqType);
                viewFxCheckDetail(dto, model, map, userId);
                map.put("businessId", affairCase.getBusinessId());
                //model.addAttribute("businessId", affairCase.getBusinessId());
            } else {
                dto.setApplicantType(affairCase.getApplicantType());
                JsonUtil jsonUtil = viewLcDetail(dto, model, map);
                return jsonUtil;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonUtil.sucessWithData("返回数据成功", map);
//        return url;

    }


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
     * @Date:11:50 2020/12/8
     */
    @PostMapping(value = "/updateCheckJlNB")
    @ResponseBody
    @TokenCheck
    public JsonUtil updateCheckJlNB(@RequestBody AffairCaseDTO dto) {
        JsonUtil re = new JsonUtil();
        try {
//            Subject sub = SecurityUtils.getSubject();
//            CurrentUser currentUser = (CurrentUser) sub.getPrincipal();
//            String userid = currentUser.getId();
            String userid = dto.getUserId();
            //流程变量
            Map<String, Object> variables = new HashMap<String, Object>();
            //流程实例id
            String processInstanceId = dto.getProcessInstanceId();
            // caseId
            String caseId = dto.getCaseId();
            // 任务id
            String taskId = dto.getTaskId();
            // 业务表id
            String businessId = dto.getBusinessId();
            // 审核备注
            String remark = dto.getRemark();
            // 审核状态
            String checkStatus = dto.getCheckStatus();
            // 任务名称
            String taskName = dto.getTaskName();
            if (StringUtils.isBlank(userid) || StringUtils.isBlank(processInstanceId) || StringUtils.isBlank(taskId)) {
                return JsonUtil.error("参数获取失败");
            }
            SupervisorFile file = new SupervisorFile();
            file.setId(businessId);
            file = supervisorFileService.selectByPrimaryKey(file);
            String fileType = file.getType();
            AffairCase affairCase = new AffairCase();
            affairCase.setCaseId(caseId);
            affairCase = affairCaseService.selectByPrimaryKey(affairCase);
            String applicantType = affairCase.getApplicantType();
            ZxProject zxproject = null;
            SupervisorProject project = null;
            JcProject jcproject = null;
            if ("003".equals(applicantType)) {
                zxproject = new ZxProject();
                zxproject.setId(file.getProjectId());
                zxproject = zxProjectService.selectByPrimaryKey(zxproject);
            } else if ("004".equals(applicantType)) {
                jcproject = new JcProject();
                jcproject.setId(file.getProjectId());
                jcproject = jcProjectService.selectByPrimaryKey(jcproject);
            } else {
                project = new SupervisorProject();
                project.setId(file.getProjectId());
                project = supervisorProjectService.selectByPrimaryKey(project);
            }


            //获取里程类型
            String lcType = affairCase.getLcType();
            JSONObject json = new JSONObject();
            // 环节名称
            String hjName = "";
            Boolean isfinish = false;
            if ("4".equals(checkStatus)) {
                String restr = updateCancle(lcType, processInstanceId, file);
                if (StringUtil.isNotBlank(restr)) {
                    re.setFlag(false);
                    re.setMsg(restr);
                    return re;
                } else {
                    /*撤销成功插入记录*/
                    addAffairCaseRecord(caseId, "001", "撤回", checkStatus, remark, taskId, processInstanceId, userid);
                    re.setFlag(true);
                    re.setMsg("撤销成功");
                    return re;
                }

            }
            switch (lcType) {
                case "001":
                    //监理内部审批流程--项目经理发起----总监理工程师审核----技术负责人审核
                    json = updateJlnbspLc(userid, checkStatus, variables, project, businessId, affairCase, taskName);
                    break;
                case "002":
                    //监理内部审核流程--项目经理发起----总监理工程师审核
                    json = updateJlnbshLc(userid, checkStatus, variables, project, businessId, affairCase);
                    break;
//                case "003":
//                    //监发两签  项目经理---（监理单位+业主单位）---项目经理归档
//                    json = updateJflq(userid, checkStatus, variables, project, businessId, affairCase, taskName);
//                    break;
//                case "004":
//                    //监发三签  项目经理---（监理单位+业主单位+承建单位）---项目经理归档
//                    json = updateJfsq(userid, checkStatus, variables, project, businessId, affairCase, taskName);
//                    break;
//                case "005":
//                    //承发三签  承建单位---（监理单位+业主单位+承建单位）---项目经理归档
//                    json = updateCfsq(userid, checkStatus, variables, project, businessId, fileType, affairCase, taskName);
                // break;
                case "006":
                    //部门项目经理审核
                    json = updateDeptCheck(userid, checkStatus, variables, project, businessId, affairCase);
                    break;
//                case "010":
//                    //部门项目经理审核--咨询
//                    json = updateDeptCheckZx(userid, checkStatus, variables, zxproject, businessId, affairCase);
//                    break;
//                case "011":
//                    //内部审核--咨询
//                    json = updateJlnbshLcZx(userid, checkStatus, variables, zxproject, businessId, affairCase);
//                case "012":
//                    //咨询内部审批流程--项目经理发起----行业负责人审核----技术负责人审核
//                    json = updateJlnbspLcZx(userid, checkStatus, variables, zxproject, businessId, affairCase, taskName);
//                    break;
//                case "013":
//                    //咨发两签----项目经理发起---页面单位
//                    json = updateZflqZx(userid, checkStatus, variables, zxproject, businessId, affairCase, taskName);
//                    break;
//                case "017":
//                    //部门项目经理审核--检测
//                    json = updateDeptCheckJc(userid, checkStatus, variables, jcproject, businessId, affairCase);
//                    break;
//                case "015":
//                    //审核--检测
//                    json = updateJlnbshLcJc(userid, checkStatus, variables, jcproject, businessId, affairCase);
//                    break;
//                case "016":
//                    //检测内部审批流程--项目经理发起-----技术负责人审核----授权签字人审核-
//                    json = updateJlnbspLcJc(userid, checkStatus, variables, jcproject, businessId, affairCase, taskName);
//                    break;
//                case "014":
//                    //检发两签----项目经理发起---业主单位审核
//                    json = updateJflqJz(userid, checkStatus, variables, jcproject, businessId, affairCase, taskName);
//                    break;
                default:
                    JsonUtil.error("不支持的审批流程");
                    break;
            }
            /*发送流程 某某项目流程新进展，请及时查看  进展通知*/
            /*审核人不是发起人，则给流程发起人发送消息通知*/
            String sqUserId = affairCase.getApplicantId();
            if (!userid.equals(sqUserId)) {

                if ("003".equals(applicantType)) {
                    // sendNoticeZx(affairCase, zxproject);
                } else if ("004".equals(applicantType)) {
                    // sendNoticeJc(affairCase, jcproject);
                } else {
                    sendNotice(affairCase, project);
                }

            }
            if ("003".equals(lcType) || "004".equals(lcType) || "005".equals(lcType) || "013".equals(lcType) || "014".equals(lcType)) {
                //  updateFinishWb(json, checkStatus, affairCase, variables, businessId, taskId, isfinish);
            } else {
                workflowService.completeTask(taskId, false, variables);
            }
            //插入流程记录表
            hjName = json.get("hjname") + "";
            String record = addAffairCaseRecord(caseId, applicantType, hjName, checkStatus, remark, taskId, processInstanceId, userid);
            if (json.get("isfinish") != null) {
                isfinish = (Boolean) json.get("isfinish");
            }
            //更新AffirCase
            updateAffirCase(affairCase, isfinish, record, checkStatus, remark);

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            re.setMsg("操作失败" + e.getMessage());
            re.setFlag(false);
            return re;
        }
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;
    }


    /**
     * @param affairCase
     * @param project
     * @Author:zhaoyongke
     * @Description: 发送通知
     * @Date:13:28 2021/1/22
     */
    public void sendNotice(AffairCase affairCase, SupervisorProject project) {
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(affairCase.getCaseId());
        notice.setIsView("0");
        notice.setSendTo(affairCase.getApplicantId());
        notice.setTitle(project.getProjectName() + "项目流程有新进展，请及时查看");
        notice.setNoticeType("002");//通知类型 账号通知 001  002 流程进展通知
        notice.setApplicantType("001");// 监理
        projectNoticeServie.insertSelective(notice);
    }


    /**
     * @param roleName
     * @param checkStatus
     * @param variables
     * @param project
     * @param businessId
     * @param affairCase
     * @Author:zhaoyongke
     * @Description: 监理内部审核流程 ------部门经理审核
     * @Date:13:46 2020/12/9
     */
    public JSONObject updateDeptCheck(String roleName, String checkStatus, Map<String, Object> variables, SupervisorProject project, String businessId, AffairCase affairCase) {
        JSONObject jsonObject = new JSONObject();
        String hjName = "";
        Boolean isFinish = false;
        //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
        // 部门经理审核
        if ("2".equals(checkStatus)) {
            // 审核通过
            //流程结束  内部流程审核不通过
            updateFileStatus(businessId, "2");
            //更新用章记录
            projectSealRecordService.updateSealRecord(project.getId(), businessId);
            // 完成
            isFinish = true;
        } else {
            // 审核不通过
            //流程结束  内部流程审核不通过
            updateFileStatus(businessId, "3");
            // 完成
            isFinish = true;

        }
        hjName = "部门经理审核";
        jsonObject.put("hjname", hjName);
        jsonObject.put("isfinish", isFinish);
        return jsonObject;

    }

    /**
     * @param roleName
     * @param checkStatus
     * @param variables
     * @param project
     * @param businessId
     * @param affairCase
     * @Author:zhaoyongke
     * @Description: 监理内部审核流程 ------审核
     * @Date:13:46 2020/12/9
     */
    public JSONObject updateJlnbshLc(String roleName, String checkStatus, Map<String, Object> variables, SupervisorProject project, String businessId, AffairCase affairCase) {
        JSONObject jsonObject = new JSONObject();
        String hjName = "";
        Boolean isFinish = false;
        //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
        // 总监理工程师审核
        if ("2".equals(checkStatus)) {
            // 审核通过
            //流程结束  内部流程审核不通过
            updateFileStatus(businessId, "2");
            //更新用章记录
            projectSealRecordService.updateSealRecord(project.getId(), businessId);
            // 完成
            isFinish = true;
        } else {
            // 审核不通过
            //流程结束  内部流程审核不通过
            updateFileStatus(businessId, "3");
            // 完成
            isFinish = true;

        }
        hjName = "总监理工程师审核";
        jsonObject.put("hjname", hjName);
        jsonObject.put("isfinish", isFinish);
        return jsonObject;

    }


    /**
     * @param
     * @param checkStatus
     * @param variables
     * @param project
     * @param businessId
     * @Author:zhaoyongke
     * @Description: 监理内部审批流程处理 ------审核  流程类型 001
     * @Date:14:52 2020/12/8
     */
    public JSONObject updateJlnbspLc(String userId, String checkStatus, Map<String, Object> variables, SupervisorProject project, String businessId, AffairCase affairCase, String taskName) {
        JSONObject jsonObject = new JSONObject();
        String hjName = "";
        Boolean isFinish = false;
        //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
        if ("总监理工程师审核".equals(taskName)) {
            // 总监理工程师审核
            if ("2".equals(checkStatus)) {
                // 审核通过
                variables.put("zjchek", "1");
                //下一步技术负责人审核
                String jsuserid = project.getTechnologyPerson();
                variables.put("js", jsuserid);
            } else {
                // 审核不通过
                variables.put("zjchek", "-1");
                //流程结束  内部流程审核不通过
                updateFileStatus(businessId, "3");
                //完成
                isFinish = true;

            }
            hjName = "总监理工程师审核";
        } else if ("技术负责人审核".equals(taskName)) {
            // 技术负责人审核
            if ("2".equals(checkStatus)) {
                //流程结束 审核通过
                updateFileStatus(businessId, "2");
                //更新用章记录
                projectSealRecordService.updateSealRecord(project.getId(), businessId);
                //完成
                isFinish = true;
            } else {
                //流程结束 审核不通过
                variables.put("zjchek", "-1");
                //内部流程审核不通过
                updateFileStatus(businessId, "3");
                //完成
                isFinish = true;
            }

            hjName = "技术负责人审核";

        }
        jsonObject.put("hjname", hjName);
        jsonObject.put("isfinish", isFinish);
        return jsonObject;

    }

    /**
     * @param fileId
     * @param lcstatus
     * @Author:zhaoyongke
     * @Description: 修改流程状态
     * @Date:13:20 2020/12/8
     */
    public void updateFileStatus(String fileId, String lcstatus) {
        //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
        SupervisorFile file = new SupervisorFile();
        file.setId(fileId);
        file = supervisorFileService.selectByPrimaryKey(file);
        file.setLcStatus(lcstatus);
        supervisorFileService.updateByPrimaryKey(file);
    }

    /**
     * @param lcType
     * @param processInstanceId
     * @param file
     * @Author:zhaoyongke
     * @Description:
     * @Date:17:44 2021/1/25
     */
    public String updateCancle(String lcType, String processInstanceId, SupervisorFile file) {
        String str = "";
        /*判断下一节点有没有审核*/
        AffairRecord affairRecord = new AffairRecord();
        affairRecord.setProcessInstanceId(processInstanceId);
        Integer countlcre = affairRecordService.selectCount(affairRecord);
        if (countlcre > 1) {
            str = "该流程下一节点已经被审核，不允许撤回";
            return str;
        }
        /*撤回操作*/
        runtimeService.deleteProcessInstance(processInstanceId, "撤销");
        /*修改业务表状态*/
        //流程状态0 内部未发起流程1 内部进行中 2 内部流程审核通过3内部流程审核不通过4外部流程进行中5外部流程审核通过（归档）6 外部流程审核不通过
        // 不管流程之前有没有 内部流程，统一处理成 2
        if ("003".equals(lcType) || "004".equals(lcType) || "005".equals(lcType)) {
            file.setLcStatus("2");
        } else {
            file.setLcStatus("0");
        }
        supervisorFileService.updateByPrimaryKey(file);
        // 保存流程记录
        return str;
    }

    /**
     * @param dto
     * @param model
     * @Author:zhaoyongke
     * @Description: 查看流程详情
     * @Date:14:05 2021/1/22
     */
    public JsonUtil viewLcDetail(AffairCaseDTO dto, Model model, HashMap map) throws Exception {
        String url = "";
        String caseId = dto.getCaseId();
        String taskId = dto.getTaskId();
        String yqType = dto.getLcType();// 流程查看类型 1  代办 2 已办  3 已办结 4 我的请求 5 审批进程
        String taskName = dto.getTaskName();
        String applicantType = dto.getApplicantType();
        AffairCase affairCase = new AffairCase();
        affairCase.setCaseId(caseId);
        affairCase = affairCaseService.selectByPrimaryKey(affairCase);
        //查询发起人员信息 获取申报对象Id
        String userid = affairCase.getApplicantId();
        SysUser user = new SysUser();
        user.setId(userid);
        user = sysUserService.selectByPrimaryKey(user);
        //查询文件
        String businessId = affairCase.getBusinessId();
        SupervisorFile file = new SupervisorFile();
        file.setId(businessId);
        file = supervisorFileService.selectByPrimaryKey(file);
        if (file == null) {
            return JsonUtil.error("您的文件不存在");
        }
        if ("003".equals(applicantType)) {
            //查询项目
            ZxProject project = new ZxProject();
            String projectId = file.getProjectId();
            project.setId(projectId);
            project = zxProjectService.selectByPrimaryKey(project);
            if (project == null) {
                return JsonUtil.error("项目不存在");
            }
            map.put("project", project);

        } else if ("004".equals(applicantType)) {
            //查询项目
            JcProject project = new JcProject();
            String projectId = file.getProjectId();
            project.setId(projectId);
            project = jcProjectService.selectByPrimaryKey(project);
            if (project == null) {
                return JsonUtil.error("项目不存在");

            }
            map.put("project", project);

        } else {
            //查询项目
            SupervisorProject project = new SupervisorProject();
            String projectId = file.getProjectId();
            project.setId(projectId);
            project = supervisorProjectService.selectByPrimaryKey(project);
            if (project == null) {
                return JsonUtil.error("项目不存在");
            }
            map.put("project", project);
        }
        //流程类型  监发三签等
        BaseDict lctype = DictUtil.getDictByCode(DictTypes.LCTYPE, affairCase.getLcType());

        //项目类型 监理 供需
        BaseDict ywtype = DictUtil.getDictByCode(DictTypes.APTYPE, affairCase.getApplicantType());
        map.put("affairCase", affairCase);
        map.put("file", file);
        map.put("fquser", user);
        map.put("lctype", lctype);
        map.put("ywtype", ywtype);
        map.put("taskId", taskId);
        map.put("taskName", taskName);
        // 只有代办页签的详情页面有 审批按钮
        String lc_type = affairCase.getLcType();
        //代办事项
        if ("1".equals(yqType)) {
            if ("003".equals(applicantType)) {
                doZxcheck(file, taskName, lc_type, model, map);
            } else if ("004".equals(applicantType)) {
                doJccheck(file, taskName, lc_type, model, map);
            } else {
                doJlcheck(file, taskName, lc_type, model, map);
            }

        } else if ("4".equals(yqType)) {
            /*我发起的流程  可以撤销*/
            AffairRecord affairRecord = new AffairRecord();
            affairRecord.setProcessInstanceId(affairCase.getProcessInstanceId());
            Integer countlcre = affairRecordService.selectCount(affairRecord);
            if (countlcre < 2) {
                map.put("iscx", "1");
                // model.addAttribute("iscx", '1');
            }
        }

        return JsonUtil.sucessWithData("", map);


    }


    /**
     * @param file
     * @param taskName
     * @param lc_type
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:11:18 2021/6/30
     */
    public void doJlcheck(SupervisorFile file, String taskName, String lc_type, Model model, HashMap map) throws Exception {


        //显示 审核 驳回 按钮
        map.put("lc_type", "1");
        // model.addAttribute("lc_type", '1');
        /**/
        if ("003".equals(lc_type) || "004".equals(lc_type) || "005".equals(lc_type)) {
            if ("归档".equals(taskName)) {
                //显示归档按钮
                map.put("lc_type", "3");
                model.addAttribute("lc_type", '3');
            }
        }
        /*获取当前用户的角色*/
        String roleName = supervisorProjectService.getUserRole(file.getId());
        /*签字 盖章 按钮的控制 */
        HashMap mapoper = supervisorFileService.getOperByRole(roleName, file.getId());
        if ("xmjl".equals(roleName)) {
            /*如果是项目经理角色，判断业主单位是否需要盖章  如果需要 则由 项目经理代理 业主单位盖章*/
            HashMap mapoperyz = supervisorFileService.getOperByRole("yz", file.getId());
            String yzoper = mapoperyz.get("oper") + "";
            if (StringUtil.isNotBlank(yzoper) && !"null".equals(yzoper)) {
                // 1a 只需要签字（文档右上角）  2a 只需要 盖章（封皮）  3a 盖章和签字分开（签字 右上角  盖章 封面）  4a  盖章和签字合并（表格中）
                //  5a 业主单位在盖章位置签字 项目经理上传图片后盖章
                if ("5a".equals(yzoper)) {
                    map.put("isyzqz", "1");
                    //model.addAttribute("isyzqz", '1');
                }
            }
        }
        String oper = mapoper.get("oper") + "";

        if (StringUtil.isNotBlank(oper)) {
            switch (oper) {
                case "1a":
                    /*只是需要签字的 第一种形式(右上角 文字替换)*/
                    map.put("qz", "1");
                    map.put("isqz", "1");
//                    model.addAttribute("qz", '1');
//                    model.addAttribute("isqz", '1');
                    break;
                case "2a":
                    /*只是需要盖章 第一种形式（盖章到封面）*/
                    map.put("gz", "1");
                    // model.addAttribute("gz", '1');
                    break;
                case "3a":
                    /*盖章和签字 分开*/
                    map.put("gz", "1");
                    map.put("isqz", "1");
                    // model.addAttribute("gz", '1');
                    // model.addAttribute("isqz", '1');
                    break;
                case "4a":
                    /*盖章和签字 合并*/
                    map.put("gz", "1");
                    map.put("isqz", "1");
                    //model.addAttribute("gz", '1');
                    //model.addAttribute("isqz", '1');
                    break;
                case "5a":
                    /*业主只是签字 由项目经理盖章*/
                    map.put("qz", "1");
                    map.put("isqz", "1");
                    // model.addAttribute("qz", '1');
                    // model.addAttribute("isqz", '1');
                    break;
                case "6a":
                    /*表格中只是签字*/
                    map.put("qz", "1");
                    map.put("isqz", "1");
                    // model.addAttribute("qz", '1');
                    // model.addAttribute("isqz", '1');
                    break;
                case "7a":
                    /*表格中只是盖章*/
                    map.put("gz", "1");
                    // model.addAttribute("gz", '1');
                    break;
                default:
                    break;
            }

        }

    }

    public void doZxcheck(SupervisorFile file, String taskName, String lc_type, Model model, HashMap map) throws Exception {
        //显示 审核 驳回 按钮
        map.put("lc_type", '1');
//        model.addAttribute("lc_type", '1');
        if ("归档".equals(taskName)) {
            //显示归档按钮
            map.put("lc_type", '3');
//            model.addAttribute("lc_type", '3');
        }

    }

    public void doJccheck(SupervisorFile file, String taskName, String lc_type, Model model, HashMap map) throws Exception {
        //显示 审核 驳回 按钮
        model.addAttribute("lc_type", '1');
        map.put("lc_type", '1');
        if ("归档".equals(taskName)) {
            //显示归档按钮
            map.put("lc_type", '3');
            model.addAttribute("lc_type", '3');
        }

    }

    /**
     * @param dto
     * @param model
     * @Author:zhaoyongke
     * @Description: 消息通知 详情
     * @Date:9:23 2021/1/18
     */
    @PostMapping("noticeDetail")
    @ResponseBody
    @TokenCheck
    public JsonUtil updateNoticeDetail(@RequestBody AffairCaseDTO dto, Model model) {
        try {
            HashMap map = new HashMap();
            String noticeId = dto.getCaseId();
            String userId = dto.getUserId();
            if (StringUtil.isBlank(noticeId) || StringUtil.isBlank(userId)) {
                return JsonUtil.error("参数获取失敗");
            }
            ProjectNotice notice = projectNoticeServie.selectByPrimaryKey(noticeId);
            /*是否查看过 1 已经查看 0  未查看*/
            notice.setIsView("1");
            notice.setModifyBy(userId);
            notice.setModifyDate(DateUtil.getCurrentDateString());
            projectNoticeServie.updateByPrimaryKey(notice);
            String linkId = notice.getLinkId();
            /*消息类型   001 账号通知  002 流程进展 */
            String noticeType = notice.getNoticeType();
            if ("001".equals(noticeType)) {
                /*账号*/
                viewNoticeZh(linkId, model, map);
                map.put("dto", notice);
                //model.addAttribute("dto", notice);
                //            return "/act/supervisor/zhNoticeDetail";
                return JsonUtil.sucessWithData("返回数据成功", map);
            } else {
                return JsonUtil.error("返回失敗");

            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("返回失敗");
        }


    }


    /**
     * @param linkId
     * @param model
     * @Author:zhaoyongke
     * @Description:消息查看---账号查看
     * @Date:13:58 2021/1/22
     */
    public void viewNoticeZh(String linkId, Model model, HashMap map) {
        SupervisorProject project = supervisorProjectService.selectByPrimaryKey(linkId);
        /*查询甲方账号*/
        ProjectLeaderDTO projectLeaderdto = new ProjectLeaderDTO();
        projectLeaderdto.setSupervisorProjectId(linkId);
        List<ProjectLeaderDTO> listleader = projectLeaderService.selectProjectLeaderList(projectLeaderdto);
        List<JSONObject> leader = new ArrayList<>();
        //查询业主管理员账号:
        List<SysUserDTO> sysUserDTOS = sysUserService.selectProjectAdmin(linkId);
        if (sysUserDTOS != null) {
            if (sysUserDTOS.size() > 0) {
                SysUserDTO admin = sysUserDTOS.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("realname", "管理员姓名：" + admin.getRealName());
                jsonObject.put("username", "用户名：" + admin.getUsername());
                jsonObject.put("companyname", "单位名称：" + admin.getCompanyName());
                jsonObject.put("password", "密码：12345678");
                leader.add(jsonObject);
            }

        }
        for (int i = 0; i < listleader.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("realname", "负责人姓名：" + listleader.get(i).getRealName());
            jsonObject.put("username", "用户名：" + listleader.get(i).getUsername());
            jsonObject.put("companyname", "单位名称：" + listleader.get(i).getCompanyName());
            jsonObject.put("password", "密码：12345678");
            leader.add(jsonObject);
        }
        List<JSONObject> cjlist = new ArrayList<>();
        ProjectUnitConstructionDTO unitConstructiondto = new ProjectUnitConstructionDTO();
        unitConstructiondto.setSupervisorProjectId(linkId);
        List<ProjectUnitConstructionDTO> listcj = projectUnitConstructionService.selectProjectUnitList(unitConstructiondto);
        for (int i = 0; i < listcj.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("realname", "负责人姓名：" + listcj.get(i).getRealName());
            jsonObject.put("username", "用户名：" + listcj.get(i).getUsername());
            jsonObject.put("companyname", "单位名称：" + listcj.get(i).getCompanyName());
            jsonObject.put("password", "密码：12345678");
            cjlist.add(jsonObject);
        }
        map.put("pro", project);
        map.put("leaderlist", leader);
        map.put("cjlist", cjlist);
        map.put("linkid", "linkId");
    }

    /**
     * @param dto
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:57 2021/3/27
     */
    public HashMap viewFxCheckDetail(AffairCaseDTO dto, Model model, HashMap map, String userId) throws Exception {
        String projectId = dto.getBusinessId();
        getProjectDetail(model, projectId, map, userId);
        String caseId = dto.getCaseId();
        String taskId = dto.getTaskId();
        String yqType = dto.getLcType();// 流程查看类型 1  代办 2 已办  3 已办结 4 我的请求 5 审批进程
        String taskName = dto.getTaskName();
        map.put("caseId", caseId);
        map.put("taskId", taskId);
        map.put("taskName", taskName);
//        model.addAttribute("caseId", caseId);
//        model.addAttribute("taskId", taskId);
//        model.addAttribute("taskName", taskName);
        // 2021 0906 修改 审核后刷新页面 防止出现 审核刷新后还显示 审核按钮 ，通过是否完成 事项表判断
        AffairCase affairCase = affairCaseService.selectByPrimaryKey(caseId);
        String endresult = "";
        if (affairCase != null) {
            endresult = affairCase.getEndresult();
        }
        // 查看有没有代办
        if ("1".equals(yqType) && !"1".equals(endresult)) {
            map.put("check", "1");
//            model.addAttribute("check", "1");
        }
        map.put("checkedit", "1");
//        model.addAttribute("checkedit", "1");
        return map;
    }

    /**
     * @param model
     * @param projectId
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:41 2021/3/27
     */
    public HashMap getProjectDetail(Model model, String projectId, HashMap map, String userId) {

        SupplierProjectDTO supplierProjectDTO1 = new SupplierProjectDTO();
        supplierProjectDTO1.setSupProjectId(projectId);
        List<SupplierProjectDTO> supplierProjectDTOS = supplierProjectManagerService.selectProject(supplierProjectDTO1);
        String publishType = "";
        if (supplierProjectDTOS.size() > 0) {
            SupplierProjectDTO projectDTO = supplierProjectDTOS.get(0);
            String pubComType = projectDTO.getPubComType();
            if ("001".equals(pubComType)) {
                BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(projectDTO.getPublishCompany());
                map.put("comName", baseCompany.getBcName());
                //model.addAttribute("comName", baseCompany.getBcName());
            } else {
                SysUser sysUser = sysUserService.selectByPrimaryKey(projectDTO.getPublishCompany());
                map.put("comName", sysUser.getCompanyName());
                //model.addAttribute("comName", sysUser.getCompanyName());
            }
            publishType = projectDTO.getPublishType();
            String status = projectDTO.getStatus();
            String checkStatus = projectDTO.getCheckStatus();
            if ("006".equals(status) && "1".equals(checkStatus)) {
                SupplierProjectChangeDTO changeDTO = supplierProjectManagerChangeService.getChangeProject(projectDTO);
                map.put("project", changeDTO);
                //model.addAttribute("project", changeDTO);
                //处理实施地点和人员地点要求
                getProjectPlaceChange(model, projectDTO.getSupProjectId(), changeDTO.getSupProjectChangeId(), map);
                SupplierProjectDTO dicprodto = new SupplierProjectDTO();
                BeanUtil.copyNotNullBean(changeDTO, dicprodto);
                //处理字典
                getProjectDic(model, dicprodto, map);
                // 查询文件
                // 获取文件
                SupervisorFileTemp tempfile = new SupervisorFileTemp();
                tempfile.setLinkId(changeDTO.getSupProjectChangeId());
                List<SupervisorFileTemp> selectfile = supervisorFileTempService.select(tempfile);
                map.put("filelist", selectfile);
//                model.addAttribute("filelist", selectfile);
                //是否显示变更列表（审核页面）
                map.put("bgcheck", "1");
                //model.addAttribute("bgcheck", "1");
                // 本次变更记录
                SupervisorProjectModifiedRecord record = new SupervisorProjectModifiedRecord();
                record.setSpId(changeDTO.getSupProjectChangeId());
                List<SupervisorProjectModifiedRecord> tList = null;
                Page<AffairCaseDTO> tPage = PageHelper.startPage(0, 1000);
                try {
                    tList = modifiedRecordService.selectListByPage(record);
                } catch (MyException e) {
                    e.printStackTrace();
                }
                map.put("changenow", tList);

            } else {
                map.put("project", projectDTO);
                //model.addAttribute("project", projectDTO);
                //处理实施地点和人员地点要求
                getProjectPlace(model, projectDTO.getSupProjectId(), map);
                //处理字典
                getProjectDic(model, projectDTO, map);
                // 获取文件
                SupervisorFileTemp tempfile = new SupervisorFileTemp();
                tempfile.setLinkId(projectId);
                List<SupervisorFileTemp> selectfile = supervisorFileTempService.select(tempfile);
                map.put("filelist", selectfile);

            }

            // 结果公示
            JsonUtil jggs = getJggs(projectDTO);
            Object data = jggs.getData();
            map.put("gsdetail", data);
            // 变更 已经审核通过的变更记录
            SupplierProjectChange change = new SupplierProjectChange();
            change.setSupProjectId(projectDTO.getSupProjectId());
            change.setCheckStatus("2");
            List<SupplierProjectChange> selectchange = supplierProjectManagerChangeService.select(change);
            List cahngelist = new ArrayList();
            if (selectchange != null && selectchange.size() > 0) {
                for (int i = 0; i < selectchange.size(); i++) {
                    SupplierProjectChange supplierProjectChange = selectchange.get(i);
                    String supProjectChangeId = supplierProjectChange.getSupProjectChangeId();
                    HashMap mapcahnge = new HashMap();
                    HashMap changeDetail = getChangeDetail(supProjectChangeId, mapcahnge);
                    cahngelist.add(changeDetail);
                }
            }

            map.put("changelist", cahngelist);

            // 查询表更记录
            SupplierProjectAcceptDTO acceptDTO = new SupplierProjectAcceptDTO();
            acceptDTO.setSupProjectId(projectDTO.getSupProjectId());
            acceptDTO.setAcceptOrder("1");
            SysUser sysUser = getSysUser(userId);
//            if ("001".equals(sysUser.getGxType())) {
//                //供方显示我的迎接
//                acceptDTO.setAcceptBy(userId);
//            }
            List<SupplierProjectAcceptDTO> supplierProjectAcceptDTOS = supplierProjectAcceptService.selectListAcept(acceptDTO);
            if (supplierProjectAcceptDTOS != null && supplierProjectAcceptDTOS.size() > 0) {
                for (int i = 0; i < supplierProjectAcceptDTOS.size(); i++) {
                    // 查询投标文件
                    SupplierProjectAcceptDTO acceptDTO1 = supplierProjectAcceptDTOS.get(i);
                    SupervisorFileTemp supervisorFileTemp = new SupervisorFileTemp();
                    supervisorFileTemp.setLinkId(acceptDTO1.getSupAcceptId());
                    List<SupervisorFileTemp> selectfile = supervisorFileTempService.select(supervisorFileTemp);
                    supplierProjectAcceptDTOS.get(i).setFilelist(selectfile);
                }
            }
            map.put("acceptlist", supplierProjectAcceptDTOS);

        }
        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();
        map.put("comlistOwner", alstCompanyGs);
        SysUser sysUser = getSysUser(userId);
        map.put("user", sysUser);


        //model.addAttribute("comlistOwner", alstCompanyGs);
//        String url = "";
//        if ("001".equals(publishType)) {
//            //正中内部发布
//            url = "projectManager/projectDetailXfNb";
//        } else {
//            url = "projectManager/projectDetailXfWb";
//
//        }

        return map;
    }

    public SysUser getSysUser(String userId) {
        SysUser user = sysUserService.selectByPrimaryKey(userId);
        return user;
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description: 结果公示
     * @Date:10:01 2021/10/20
     */
    public JsonUtil getJggs(SupplierProjectDTO dto) {
        HashMap map = new HashMap();
        String supProjectId = dto.getSupProjectId();
        if (StringUtils.isBlank(supProjectId)) {
            return JsonUtil.error("获取参数失败");
        }
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        SupplierProjectPubNoticeDTO noticedto = new SupplierProjectPubNoticeDTO();
        noticedto.setSupProjectId(supProjectId);
        List<SupplierProjectPubNotice> list = supplierProjectPubNoticeService.select(noticedto);
        if (list != null && list.size() > 0) {
            SupplierProjectPubNotice pubNotice = list.get(0);
            //中标单位
            String zbCompany = pubNotice.getZbCompany();
            String comType = pubNotice.getZbComType();
            //中标人
            String zbBy = pubNotice.getZbBy();
            String publish_by = project.getPublishBy();
            // 发布单位
            String pushcompany = getFbdwByUser(publish_by);
            //中标单位
            String zbcompany = getZbdwByCompanyId(zbCompany, comType);
            SysUser sysUser = sysUserService.selectByPrimaryKey(zbBy);
            //中标人
            String zbuserName = sysUser.getRealName();
            getUserJlZxJcManage(supProjectId, map);
            map.put("zbusername", zbuserName);
            map.put("zbcompany", zbcompany);
            map.put("pushcompany", pushcompany);
            map.put("supProjectId", supProjectId);
            map.put("project", project);
            map.put("pubNotice", pubNotice);

            String remark = project.getRemark();
            String publishType = project.getPublishType();
            String isConfirm = project.getIsConfirm();
            //
            if (!"001".equals(publishType)) {
                map.put("remark", remark);
                // model.addAttribute("remark",remark);
            } else if ("001".equals(publishType)) {
                if ("3".equals(isConfirm)) {
                    //
                    AffairRecord recordquerycheck = new AffairRecord();
                    recordquerycheck.setYwType("000");
                    recordquerycheck.setYwId(supProjectId);
                    List<AffairRecord> selectcheck = affairRecordService.select(recordquerycheck);
                    if (selectcheck != null) {
                        map.put("selectcheck", selectcheck);
                        //                    model.addAttribute("selectcheck",selectcheck);
                    }

                }

            }

        }


        return JsonUtil.sucessWithData("成功", map);
    }


    /**
     * @param supProjectId
     * @Author:zhaoyongke
     * @Description: 获取中标得项目经理名称
     * @Date:11:32 2021/9/6
     */
    public void getUserJlZxJcManage(String supProjectId, HashMap map) {

        //2021 0906  获取项目经理等信息
        SupplierProjectAccept notdto = new SupplierProjectAccept();
        notdto.setSupProjectId(supProjectId);
        notdto.setIsZb("1");
        List<SupplierProjectAccept> list = supplierProjectAcceptService.select(notdto);
        if (list != null) {
            if (list.size() > 0) {
                SupplierProjectAccept accept = list.get(0);
                if (accept != null) {
                    String jlManagerPerson = accept.getJlManagerPerson();
                    if (StringUtil.isNotBlank(jlManagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(jlManagerPerson);
                        if (sysUser1 != null) {
                            String jlmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if (StringUtil.isNotBlank(realName)) {
                                map.put("jlmanagename", realName);
                                //  model.addAttribute("jlmanagename",realName);
                            } else {
                                map.put("jlmanagename", jlmanagename);
//                                model.addAttribute("jlmanagename",jlmanagename);
                            }

                        }
                    }
                    String jcManagerPerson = accept.getJcManagerPerson();
                    if (StringUtil.isNotBlank(jcManagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(jcManagerPerson);
                        if (sysUser1 != null) {
                            String jcmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if (StringUtil.isNotBlank(realName)) {
                                map.put("jcmanagename", realName);
                                // model.addAttribute("jcmanagename",realName);
                            } else {
                                map.put("jcmanagename", jcmanagename);
                                // model.addAttribute("jcmanagename",jcmanagename);
                            }


                        }
                    }
                    String zxManagerPerson = accept.getZxManagerPerson();
                    if (StringUtil.isNotBlank(zxManagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(zxManagerPerson);
                        if (sysUser1 != null) {
                            String zxmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if (StringUtil.isNotBlank(realName)) {

                                map.put("zxmanagename", realName);
                                //   model.addAttribute("zxmanagename",realName);
                            } else {
                                map.put("zxmanagename", zxmanagename);
                                // model.addAttribute("zxmanagename",zxmanagename);
                            }

                        }
                    }
                    String qtMagagerPerson = accept.getQtMagagerPerson();
                    if (StringUtil.isNotBlank(qtMagagerPerson)) {
                        SysUser sysUser1 = sysUserService.selectByPrimaryKey(qtMagagerPerson);
                        if (sysUser1 != null) {
                            String qtmanagename = sysUser1.getUsername();
                            String realName = sysUser1.getRealName();
                            if (StringUtil.isNotBlank(realName)) {
                                map.put("qtmanagename", realName);
//                                model.addAttribute("qtmanagename",realName);
                            } else {
                                map.put("qtmanagename", qtmanagename);
                                // model.addAttribute("qtmanagename",qtmanagename);
                            }

                        }
                    }
                }
                //

            }
        }
    }


    /**
     * @param companyId
     * @param comtype
     * @Author:zhaoyongke
     * @Description: 获取中标单位
     * @Date:10:31 2021/4/7
     */
    public String getZbdwByCompanyId(String companyId, String comtype) {
        String companyName = "";
        if ("001".equals(comtype)) {
            //001 保存的是公司表Id
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
            companyName = baseCompany.getBcName();
        } else {
            SysUser sysUser = sysUserService.selectByPrimaryKey(companyId);
            companyName = sysUser.getCompanyName();
        }
        return companyName;

    }

    public HashMap getChangeDetail(String supProjectChangeId, HashMap map) {

        SupplierProjectChange supplierProjectChange = supplierProjectManagerChangeService.selectByPrimaryKey(supProjectChangeId);
        String supProjectId = supplierProjectChange.getSupProjectId();
        SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
        if (StringUtil.isNotBlank(supplierProjectChange.getProjectType())) {
            //項目類型
            String proTypestr = getLxText(supplierProjectChange.getProjectType(), DictTypes.YW_TYPE.getType());
            map.put("strprojecttype", proTypestr);
        }
        String createBy = project.getCreateBy();
        String companyName = getFbdwByUser(createBy);
        SysUser sysUser1 = sysUserService.selectByPrimaryKey(createBy);
        map.put("user", sysUser1);
        map.put("project", project);
        map.put("companyName", companyName);
        map.put("change", supplierProjectChange);
        map.put("supProjectChangeId", supplierProjectChange.getSupProjectChangeId());
        // 查询修改记录
        List<SupervisorProjectModifiedRecord> tList = null;
        Page<AffairCaseDTO> tPage = PageHelper.startPage(0, 1000);
        SupervisorProjectModifiedRecord record = new SupervisorProjectModifiedRecord();
        record.setSpId(supProjectChangeId);
        try {
            List<SupervisorProjectModifiedRecord> list = modifiedRecordService.selectListByPage(record);
            map.put("list", list);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return map;
    }


    /**
     * @param userId
     * @Author:zhaoyongke
     * @Description: 获取发布单位
     * @Date:10:24 2021/4/7
     */
    public String getFbdwByUser(String userId) {
        String companyName = "";
        SysUser sysUser = sysUserService.selectByPrimaryKey(userId);
        String source = sysUser.getSource();
        if ("001".equals(source)) {
            // 正中人员
            String companyId = sysUser.getCompanyName();
            BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(companyId);
            companyName = baseCompany.getBcName();
        } else {
            companyName = sysUser.getCompanyName();
        }
        return companyName;

    }


    /**
     * @param model
     * @param projectId
     * @param proChangeId
     * @Author:zhaoyongke
     * @Description: 获取变更后的地点
     * @Date:15:43 2021/3/29
     */
    public void getProjectPlaceChange(Model model, String projectId, String proChangeId, HashMap map) {
        // 实施地点
        ProjectPlaceChangeDTO dto = new ProjectPlaceChangeDTO();
        dto.setSupProjectId(projectId);
        dto.setSupProjectChangeId(proChangeId);
        dto.setType("001");
        List<ProjectPlaceChangeDTO> listpalce = projectPlaceChangeService.selectPlace(dto);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist);
        }
        map.put("listpalce", listpalce);
        // model.addAttribute("listpalce", listpalce);
        // 人员地点
        ProjectPlaceChangeDTO dtopersonplace = new ProjectPlaceChangeDTO();
        dtopersonplace.setSupProjectId(projectId);
        dtopersonplace.setSupProjectChangeId(proChangeId);
        dtopersonplace.setType("002");
        List<ProjectPlaceChangeDTO> listPersonPalce = projectPlaceChangeService.selectPlace(dtopersonplace);
        for (int i = 0; i < listPersonPalce.size(); i++) {
            String province = listPersonPalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listPersonPalce.get(i).setCitys(citylist);
            String city = listPersonPalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listPersonPalce.get(i).setCountys(countylist);
        }
        map.put("listperpalce", listPersonPalce);
//        model.addAttribute("listperpalce", listPersonPalce);
    }


    /**
     * @param model
     * @Author:zhaoyongke
     * @Description:
     * @Date:14:25 2021/3/24
     */
    public void getProjectDic(Model model, SupplierProjectDTO dto, HashMap map) {
        // 学历类型
        List<BaseDict> edulist = baseDictService.selectByTypeCode("XL001");
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.YW_TYPE);
        /*行业类型*/
        List<BaseDict> hyTypeList = DictUtil.getDictByType(DictTypes.INDUSTRY);
        //擅长领域
        List<BaseDict> doBestList = baseDictService.selectByTypeCode(DictTypes.DOBEST.getType());
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");

        if (StringUtil.isNotBlank(dto.getMainFzField())) {
            String mainFzFieldstr = getLxText(dto.getMainFzField(), DictTypes.DOBEST.getType());
            map.put("strbest", mainFzFieldstr);
            //model.addAttribute("strbest", mainFzFieldstr);
        }
        if (StringUtil.isNotBlank(dto.getProjectType())) {
            //項目類型
            String proTypestr = getLxText(dto.getProjectType(), DictTypes.YW_TYPE.getType());
            map.put("strprojecttype", proTypestr);
            //model.addAttribute("strprojecttype", proTypestr);
        }
        if (StringUtil.isNotBlank(dto.getHyType())) {
            //行业类型
            String hyTypestr = getLxText(dto.getHyType(), DictTypes.INDUSTRY.getType());
            map.put("hyTypestr", hyTypestr);
            //model.addAttribute("hyTypestr", hyTypestr);
        }
        // 市
        List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(dto.getHtSignProvince());
        // 县
        List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(dto.getHtSignCity());

        map.put("citylist", citylist);
        map.put("countylist", countylist);
        map.put("projectTypeList", projectTypeList);
        map.put("hytypelist", hyTypeList);
        map.put("provincelist", provincelist);
        map.put("edulist", edulist);
        map.put("doBestList", doBestList);
//        model.addAttribute("citylist", citylist);
//        model.addAttribute("countylist", countylist);
//        model.addAttribute("projectTypeList", projectTypeList);
//        model.addAttribute("hytypelist", hyTypeList);
//        model.addAttribute("provincelist", provincelist);
//        model.addAttribute("edulist", edulist);
//        model.addAttribute("doBestList", doBestList);
    }

    public String getLxText(String field, String typecode) {
        List<BaseDict> codeList = baseDictService.selectByTypeCode(typecode);
        HashMap<String, String> mapbest = new HashMap();
        for (int i = 0; i < codeList.size(); i++) {
            mapbest.put(codeList.get(i).getBadtCode(), codeList.get(i).getBadtName());
        }
        //擅长领域
        List<String> dobest = StringUtil.split(field);
        List<String> best = new ArrayList<>();
        for (int i = 0; i < dobest.size(); i++) {
            String s = dobest.get(i);
            String scname = mapbest.get(s);
            best.add(scname);
        }
        String strbest = best.toString().replaceAll("\\[", "").replaceAll("\\]", "");
        return strbest;

    }


    /**
     * @param model
     * @param projectId
     * @Author:zhaoyongke
     * @Description:
     * @Date:14:29 2021/3/24
     */
    public void getProjectPlace(Model model, String projectId, HashMap map) {
        // 实施地点
        ProjectPlaceDTO dto = new ProjectPlaceDTO();
        dto.setSupProjectId(projectId);
        dto.setType("001");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(dto);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist);
        }
        map.put("listpalce", listpalce);
        // model.addAttribute("listpalce", listpalce);
        // 人员地点
        ProjectPlaceDTO dtopersonplace = new ProjectPlaceDTO();
        dtopersonplace.setSupProjectId(projectId);
        dtopersonplace.setType("002");
        List<ProjectPlaceDTO> listPersonPalce = projectPlaceService.selectPlace(dtopersonplace);
        for (int i = 0; i < listPersonPalce.size(); i++) {
            String province = listPersonPalce.get(i).getProvince();
            List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(province);
            listPersonPalce.get(i).setCitys(citylist);
            String city = listPersonPalce.get(i).getCity();
            List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(city);
            listPersonPalce.get(i).setCountys(countylist);
        }
        map.put("listperpalce", listPersonPalce);
        //model.addAttribute("listperpalce", listPersonPalce);
    }


    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:供需 项目审核
     * @Date:17:29 2021/3/29
     */
    @PostMapping(value = "/updateCheckGxCheck")
    @ResponseBody
    @TokenCheck
    public JsonUtil updateCheckGxCheck(@RequestBody AffairCaseDTO dto) {
        JsonUtil re = new JsonUtil();
        try {
            Subject sub = SecurityUtils.getSubject();
            String userId = dto.getUserId();

            //流程变量
            Map<String, Object> variables = new HashMap<String, Object>();
            //流程实例id
            String processInstanceId = dto.getProcessInstanceId();
            // caseId
            String caseId = dto.getCaseId();
            // 任务id
            String taskId = dto.getTaskId();
            // 业务表id
            String businessId = dto.getBusinessId();
            // 审核备注
            String remark = dto.getRemark();
            // 审核状态
            String checkStatus = dto.getCheckStatus();
            // 任务名称
            String taskName = dto.getTaskName();
            if (StringUtils.isBlank(userId) || StringUtils.isBlank(caseId) || StringUtils.isBlank(taskId)) {
                re.setFlag(false);
                re.setMsg("操作失败");
                return re;
            }
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(businessId);
            // 项目名称 001 已保存 002 待审核 003 已驳回 004 已结束 005 已撤销  006 已发布
            String status = project.getStatus();
            if ("006".equals(status)) {
                //提交后从临时文件表 移动到正式文件表中
                String copyZskUrl = supervisorFileTempService.getCopyZskUrl(project);
                SupervisorFileTemp temp = new SupervisorFileTemp();
                temp.setLinkId(project.getSupProjectId());
                List<SupervisorFileTemp> selectfilelist = supervisorFileTempService.select(temp);
                supervisorFileTempService.updateCopyFileToZsk(copyZskUrl, project, selectfilelist);
                project.setZskurl(copyZskUrl);
                affairService.updateGxChangeProject(checkStatus, project, "001");
            } else {
                if ("2".equals(checkStatus)) {
                    //提交后从临时文件表 移动到正式文件表中
                    String copyZskUrl = supervisorFileTempService.getCopyZskUrl(project);
                    SupervisorFileTemp temp = new SupervisorFileTemp();
                    temp.setLinkId(project.getSupProjectId());
                    List<SupervisorFileTemp> selectfilelist = supervisorFileTempService.select(temp);
                    supervisorFileTempService.updateCopyFileToZsk(copyZskUrl, project, selectfilelist);
                    project.setZskurl(copyZskUrl);
                    project.setStatus("006");//已发布
                    project.setPublishDate(DateUtil.getCurrentDateString());
                } else {
                    project.setStatus("003");//已驳回

                }
            }
            project.setCheckStatus(checkStatus);
            project.setCheckRemark(remark);
            String currentDateString = DateUtil.getCurrentDateString();
            project.setCheckDate(currentDateString);
            project.setCheckBy(userId);
            supplierProjectManagerService.updateByPrimaryKey(project);
            AffairCase affairCase = new AffairCase();
            affairCase.setCaseId(caseId);
            affairCase = affairCaseService.selectByPrimaryKey(affairCase);
            workflowService.completeTask(taskId, false, variables);
            String record = addAffairCaseRecord(caseId, "002", "发布审核", checkStatus, remark, taskId, processInstanceId, userId);
//            //更新AffirCase
            updateAffirCase(affairCase, true, record, checkStatus, remark);
//            // 给发布人消息提醒
            sendNoticeCheckGx(affairCase, project, checkStatus, userId);
            //给审核人消息提醒
            //sendNoticeReviewer(affairCase,project,checkStatus);
            List<String> ids = sysUserService.selectUserIdListForPushMsg(userId);
            for (String id : ids) {
                affairCase = new AffairCase();
                affairCase.setApplicantId(id);
                sendNoticeReviewer(affairCase, project, checkStatus);
            }


        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            re.setMsg("操作失败" + e.getMessage());
            re.setFlag(false);
            return re;
        }
        re.setFlag(true);
        re.setMsg("操作成功");
        return re;


    }


    /**
     * @param affairCase
     * @param project
     * @param checkStatus
     */
    public void sendNoticeReviewer(AffairCase affairCase, SupplierProject project, String checkStatus) {
        String checkresult = "";
        if ("2".equals(checkStatus)) {
            checkresult = "通过";
        } else {
            checkresult = "不通过";
        }
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(affairCase.getApplicantId());
        notice.setTitle(project.getProjectName() + "项目审核" + checkresult + "，请及时查看");
        notice.setNoticeType("112");//通知类型 账号通知 001  002 流程进展通知
        notice.setApplicantType("002");// 供需
        projectNoticeServie.insertSelective(notice);
    }


    public String addAffairCaseRecord(String ywId, String ywType, String hjName, String checkStatus, String remark, String taskId, String processInstanceId, String userId) {
        AffairRecordDTO dto = new AffairRecordDTO();
        // 业务Id
        dto.setYwId(ywId);
        /**
         * 业务类型 001 监理系统 002 供需 0
         */
        dto.setYwType(ywType);
        //环节名称
        dto.setHjName(hjName);
        //审核状态 1 提交 2 审核通过 3 审核不通过

        dto.setCheckStatus(checkStatus);
        //备注
        dto.setRemark(remark);
        // 任务id
        dto.setTaskId(taskId);
        // 工作流实例id
        dto.setProcessInstanceId(processInstanceId);
        String recordId = workflowService.addAffairCaseRecordApp(dto, userId);
        return recordId;

    }

    /**
     * @param affairCase
     * @Author:zhaoyongke
     * @Description: 更新affircase
     * @Date:17:01 2020/12/8
     */
    public void updateAffirCase(AffairCase affairCase, Boolean isfinsih, String recordId, String checkStatus, String remark) {
        if (isfinsih) {
            affairCase.setEndresult("1");
            affairCase.setEndTime(DateUtil.formatDate(new Date()));
            if ("3".equals(checkStatus)) {
                //审核不通过 审核备注
                affairCase.setMemo(remark);
            }
        }

        affairCase.setCurrRecordId(recordId);
        affairCaseService.updateByPrimaryKey(affairCase);
    }

    /**
     * @param affairCase
     * @param project
     * @Author:zhaoyongke
     * @Description:项目审核通过 或 驳回 消息提醒
     * @Date:17:21 2021/9/6
     */
    public void sendNoticeCheckGx(AffairCase affairCase, SupplierProject project, String checkStatus, String userId) {
        String checkresult = "";
        if ("2".equals(checkStatus)) {
            checkresult = "通过";
        } else {
            checkresult = "不通过";
        }
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(project.getSupProjectId());
        notice.setIsView("0");
        notice.setSendTo(affairCase.getApplicantId());
        notice.setTitle(project.getProjectName() + "项目审核" + checkresult + "，请及时查看");
        notice.setNoticeType("110");//通知类型 账号通知 001  002 流程进展通知
        notice.setApplicantType("002");// 供需
        notice.setCreateBy(userId);
        projectNoticeServie.insertSelective(notice);
    }

    /**
     * @Author:zhaoyongke
     * @Description:
     * @Date:15:08 2021/10/22
     */
    @PostMapping(value = "/updateNotice")
    @ResponseBody
    @TokenCheck
    public JsonUtil updateNotice(@RequestBody AffairCaseDTO dto) {
        try {
            String caseId = dto.getCaseId();
            if (StringUtil.isNotBlank(caseId)) {
                // 处理消息 为已看
                ProjectNotice projectNotice = projectNoticeServie.selectByPrimaryKey(caseId);
                projectNotice.setIsView("1");
                projectNoticeServie.updateByPrimaryKey(projectNotice);
            } else {
                return JsonUtil.error("參數失败");
            }
            return JsonUtil.sucess("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("失败");
        }
    }

    /**
     * @param dto
     * @Author:zhaoyongke
     * @Description:
     * @Date:17:50 2021/10/22
     */
    @PostMapping(value = "/selectNoticeGroupUser")
    @ResponseBody
    @TokenCheck
    public JsonUtil selectNoticeGroupUser(@RequestBody ProjectNoticeDTO dto) {
        try {
            List<ProjectNoticeDTO> projectNoticeDTOS = null;
            String userId = dto.getUserId();
            if (StringUtil.isNotBlank(userId)) {
                projectNoticeDTOS = projectNoticeServie.selectNoticeGroup(dto);
                if (projectNoticeDTOS != null && projectNoticeDTOS.size() > 0) {
                    for (int i = 0; i < projectNoticeDTOS.size(); i++) {
                        ProjectNoticeDTO projectNoticeDTO = projectNoticeDTOS.get(i);
                        String applicantType = projectNoticeDTO.getApplicantType();
                        if ("001".equals(applicantType) || "002".equals(applicantType) || "000".equals(applicantType)) {
                            // 监理 、供需  查询第一条消息
                            AffairCaseDTO notice = new AffairCaseDTO();
                            notice.setSendTo(userId);
                            notice.setApplicantType(applicantType);
                            List<AffairCaseDTO> affairCaseDTOS = affairService.queryMyNoticeApp(notice);
                            if (affairCaseDTOS != null && affairCaseDTOS.size() > 0) {
                                AffairCaseDTO affairCaseDTO = affairCaseDTOS.get(0);
                                projectNoticeDTOS.get(i).setAffairCaseDTO(affairCaseDTO);
                            }
                        }

                    }
                }
            } else {
                return JsonUtil.error("參數失败");
            }
            return JsonUtil.sucessWithData("成功", projectNoticeDTOS);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error("失败");
        }
    }


}
